import { onMounted, onUnmounted, ref } from 'vue'
import { throttle } from 'underscore'
// 监听window窗口滚动
// 1.当我们离开页面时, 我们移除监听
// 2.如果别的页面类似监听, 会重复代码
// export default function useScroll(reachButtonCB) {
//   const scrollListenerHandler = () => {
//     const clientHeight = document.documentElement.clientHeight
//     const scrollTop = document.documentElement.scrollTop
//     const scrollHeight = document.documentElement.scrollHeight
//     if (clientHeight + scrollTop + 1 >= scrollHeight) {
//       console.log('滚动到底部了')
//       if (reachButtonCB) reachButtonCB()
//     }
//   }
  
//   onMounted(() => {
//     window.addEventListener('scroll',scrollListenerHandler)
//   })
  
//   onUnmounted(() => {
//     window.removeEventListener('scroll',scrollListenerHandler)
//   })
// }

export default function useScroll() {
  const isReachBottom = ref(false)
  const clientHeight = ref(0)
  const scrollTop = ref(0)
  const scrollHeight = ref(0)


  // 防抖/节流
  const scrollListenerHandler = throttle(() => {
      clientHeight.value = document.documentElement.clientHeight
      scrollTop.value = document.documentElement.scrollTop
      scrollHeight.value = document.documentElement.scrollHeight
      console.log('监听到滚动')
      if (clientHeight.value + scrollTop.value + 1 >= scrollHeight.value) {
        console.log('滚动到底部了')
        isReachBottom.value = true
      }
  }, 100)
  
  onMounted(() => {
    window.addEventListener('scroll',scrollListenerHandler)
  })
  
  onUnmounted(() => {
    window.removeEventListener('scroll',scrollListenerHandler)
  })

  return { isReachBottom, clientHeight, scrollHeight, scrollTop }
}